package com.xxlie.auth.endpoint;

import com.xxlie.auth.common.CommUtil;
import com.xxlie.auth.model.AttachBean;
import com.xxlie.auth.thirdpart.alitools.AliyunOssTool;
import com.xxlie.core.common.StringUtils;
import com.xxlie.core.model.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/common/file")
public class FileEndpoint {
    @Autowired
    AliyunOssTool aliyunOssTool;

    /**
     * 图片上传请求，image要求为Base64字节流数据，压缩格式为jpg
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/upload/base64", method = RequestMethod.POST)
    public View uploadImageBase64(HttpServletRequest request, HttpServletResponse response, @RequestBody AttachBean attachBean) {
        View view = new View(20000, "上传成功");

        String image = attachBean.getPath();

        String saveFilePathName = request.getSession().getServletContext().getRealPath("/") + File.separator + "app" + File.separator;
        File dir = new File(saveFilePathName);
        if (!dir.exists()) {
            dir.mkdir();
        }
        if (image != null && !image.equals("")) {
            //将base64转换为二进制
            image = image.replaceAll("data:image/jpeg;base64,", "");
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码
            byte[] imageByte = null;
            try {
                imageByte = decoder.decodeBuffer(image);
                for (int i = 0; i < imageByte.length; ++i) {
                    if (imageByte[i] < 0) {// 调整异常数据
                        imageByte[i] += 256;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //将二进制存储到文件中
            String fileName = UUID.randomUUID().toString() + "." + "jpg";
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(saveFilePathName + File.separator + fileName);

                fout.write(imageByte);
                File file = new File(saveFilePathName + File.separator + fileName);
                BufferedImage bis = ImageIO.read(file);
                if (bis != null) {
                    // 上传头像到阿里云OSS
                    String storeFileName = "app/" + fileName;
                    boolean uploadSuccess = aliyunOssTool.uploadFile(saveFilePathName + File.separator + fileName, storeFileName);

                    if (uploadSuccess == false) {
                        view.setCode(40000);
                        view.setMessage("上传失败，请稍后重试1");
                    } else {
                        Map map = new HashMap();
                        map.put("path", storeFileName);
                        map.put("pathFull", CommUtil.getFileUrl(storeFileName));
                        view.setData(map);
                    }
                } else {
                    view.setCode(40000);
                    view.setMessage("上传失败，请稍后重试2");
                }
            } catch (IOException e) {
                view.setCode(40000);
                view.setMessage("文件存储失败，请稍后重试");
                e.printStackTrace();
            } finally {
                if (fout != null) {
                    try {
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            view.setCode(40000);
            view.setMessage("请传递参数");
        }

        return view;
    }

    /**
     * 图片上传请求，form表单形式上传
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/upload/image", method = RequestMethod.POST)
    public View uploadImage(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file") MultipartFile image) {
        View view = new View(20000, "上传成功");

        String saveFilePathName = request.getSession().getServletContext()
                .getRealPath("/")
                + File.separator
                + "app"
                + File.separator;
        File dir = new File(saveFilePathName);
        if (!dir.exists()) {
            dir.mkdir();
        }
        if (image != null && !image.equals("")) {
            //将二进制存储到文件中
            String fileName = UUID.randomUUID().toString() + "." + "jpg";
            try {
                //将图片存储到本地
                File dest = new File(saveFilePathName + File.separator + fileName);
                image.transferTo(dest);
                //读取本地图片
                File file = new File(saveFilePathName + File.separator + fileName);
                BufferedImage bis = ImageIO.read(file);
                if (bis != null) {
                    // 上传头像到阿里云OSS
                    String storeFileName = "app/" + fileName;
                    boolean uploadSuccess = aliyunOssTool.uploadFile(saveFilePathName + File.separator + fileName, storeFileName);

                    if (uploadSuccess == false) {
                        view.setCode(40000);
                        view.setMessage("上传失败，请稍后重试");
                    } else {
                        Map map = new HashMap();
                        map.put("path", storeFileName);
                        map.put("pathFull", CommUtil.getFileUrl(storeFileName));
                        view.setData(map);
                    }
                } else {
                    view.setCode(40000);
                    view.setMessage("上传失败，请稍后重试");
                }
            } catch (IOException e) {
                view.setCode(40000);
                view.setMessage("文件存储失败，请稍后重试");
                e.printStackTrace();
            } finally {
            }
        } else {
            view.setCode(40000);
            view.setMessage("请传递参数");
        }

        return view;
    }

    /**
     * 上传附件，form表单形式上传
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/upload/attach", method = RequestMethod.POST)
    public View uploadAttach(HttpServletRequest request,
                             HttpServletResponse response,
                             @RequestParam(value = "file") MultipartFile file, @NotNull Integer type) {
        View view = new View(20000, "上传成功");

        String saveFilePathName = request.getSession().getServletContext().getRealPath("/") + "pc";
        File dir = new File(saveFilePathName);
        if (!dir.exists()) {
            dir.mkdir();
        }
        if (file != null && !file.isEmpty()) {

            String extend = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            String fileName = UUID.randomUUID().toString() + "." + extend;

            if (fileName.lastIndexOf(".") < 0) {
                fileName = fileName + "." + extend;
            }

            File dest = new File(saveFilePathName + File.separator + fileName);

            try {
                file.transferTo(dest);
            } catch (IllegalStateException | IOException e) {
                view.setCode(40000);
                view.setMessage("文件写入失败，请稍后重试");
            }

            // 上传文件到阿里云OSS
            String storeFileName = "pc/" + fileName;

            boolean uploadSuccess = true;

            uploadSuccess = aliyunOssTool.uploadFile(saveFilePathName
                    + File.separator + fileName, storeFileName);

            if (uploadSuccess == false) {
                view.setCode(40000);
                view.setMessage("上传阿里云失败，请稍后重试");
            } else {
                Map map = new HashMap();
                map.put("path", storeFileName);
                if (type == 0) {
                    map.put("pathFull", CommUtil.getFileUrl(storeFileName));
                } else {
                    map.put("pathFull",
                            aliyunOssTool.getVideoUrl(storeFileName));
                }
                view.setData(map);
            }
        } else {
            view.setCode(40000);
            view.setMessage("请传递参数");
        }

        return view;
    }

    /**
     * 附件下载
     *
     * @param request
     * @param response
     * @storeFileName
     */
    @RequestMapping(value = "/download/attach", method = RequestMethod.GET)
    public void downloadAttach(HttpServletRequest request,
                               HttpServletResponse response,
                               @RequestParam(value = "storeFileName") String storeFileName) {

        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + storeFileName);

        if (!StringUtils.isBlank(storeFileName)) {
            aliyunOssTool.downloadAttach(response, storeFileName);
        }
    }
}
